//
//  AddNewItemViewController.m
//  linkingGame
//
//  Created by zw wu on 15/5/10.
//  Copyright (c) 2015年 com.jinWu. All rights reserved.
//

#import "AddNewItemViewController.h"
#import "AddItemTip.h"
#import "AddItemCell.h"

@interface AddNewItemViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,AddItemCellDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,retain) AddItemTip *addItemTip;
@property (nonatomic,retain) UICollectionView *collectionView;
@property (nonatomic,retain) NSMutableArray *imageList;

@end

@implementation AddNewItemViewController

- (BOOL)prefersStatusBarHidden
{
    return YES;//隐藏为YES，显示为NO
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self resetAllSubViewFrame];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)])
    {
        [self prefersStatusBarHidden];
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
    }
    
    self.view.backgroundColor = [UIColor grayColor];
    
    AddItemTip *addItemTip = [[AddItemTip alloc]init];
    [self.view addSubview:addItemTip];
    self.addItemTip = addItemTip;
    [addItemTip release];
    
    addItemTip.backgroundColor = [UIColor orangeColor];
    
    [addItemTip.backBtn addTarget:self action:@selector(goToBack) forControlEvents:UIControlEventTouchUpInside];
    
    NSMutableArray *itemList = [[NSMutableArray alloc]initWithCapacity:0];
    self.imageList = itemList;
    [itemList release];
    
    [self refreshTableUI];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
                                                         collectionViewLayout:flowLayout];
    
    self.collectionView = collectionView;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    [flowLayout release];
    [collectionView release];
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    //注册cell和ReusableView（相当于头部）
    [self.collectionView registerClass:[AddItemCell class] forCellWithReuseIdentifier:@"KAddItemCell"];
}

- (BOOL)isFileExistAtPath:(NSString*)fileFullPath
{
    BOOL isExist = NO;
    isExist = [[NSFileManager defaultManager] fileExistsAtPath:fileFullPath];
    return isExist;
}

- (void)refreshTableUI
{
    [self.imageList removeAllObjects];
    
    if (self.pathId)
    {
        NSArray *paths = [self getImagePathListForFolderName:self.pathId];
        [self.imageList addObjectsFromArray:paths];
    }
    
    [self.imageList addObject:@"AddNewItemViewController_Add"];
    [self.collectionView reloadData];
}

- (NSString *)getImageFolderPath:(NSString *)folderName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"linkingGameOwnExpression"];
    NSString *folderPath = [path stringByAppendingPathComponent:folderName];
    return folderPath;
}

- (NSArray *)getImagePathListForFolderName:(NSString *)folderName
{
    NSString *folderPath = [self getImageFolderPath:folderName];
    NSArray *tmplist = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:nil];
    
    NSMutableArray *imagePathList = [NSMutableArray arrayWithCapacity:0];
    for (NSString *filename in tmplist)
    {
        NSString *fullPath = [folderPath stringByAppendingPathComponent:filename];
        if ([self isFileExistAtPath:fullPath])
        {
            [imagePathList addObject:fullPath];
        }
    }
    
    return imagePathList;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    self.pathId = nil;
    self.addItemTip = nil;
    self.collectionView = nil;
    self.imageList = nil;
    
    [super dealloc];
}

- (void)resetAllSubViewFrame
{
    CGSize mainSize = self.view.bounds.size;
    CGRect addStyleTipViewRect,collectionViewRect;
    if (isPhone())
    {
        addStyleTipViewRect = CGRectMake(0, 0, mainSize.width, 88);
    }
    else
    {
        if (isLandscape())
        {
            addStyleTipViewRect = CGRectMake(0, 0, mainSize.width, 120);
        }
        else
        {
            addStyleTipViewRect = CGRectMake(0, 0, mainSize.width, 180);
        }
    }
    
    collectionViewRect = CGRectMake(0, addStyleTipViewRect.size.height, mainSize.width, mainSize.height - addStyleTipViewRect.size.height);
    
    if (!CGRectEqualToRect(addStyleTipViewRect, self.addItemTip.frame))
    {
        self.addItemTip.frame = addStyleTipViewRect;
        [self.addItemTip refreshUI];
    }
    
    if (!CGRectEqualToRect(collectionViewRect, self.collectionView.frame))
    {
        self.collectionView.frame = collectionViewRect;
    }
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [self resetAllSubViewFrame];
}

- (void)goToBack
{
    if (self.imageList.count < KMinItemCount + 1)
    {
        NSString *tipTitle = NSLocalizedString(@"add_style_min_title",nil);
        NSString *tipMsg = NSLocalizedString(@"add_style_min_msg",nil);
        NSString *cancelBtnTitle = NSLocalizedString(@"cancel",nil);
        NSString *comfirmBtnTitle = NSLocalizedString(@"comfirm",nil);
        
        if (IOS_VERSION_8_OR_ABOVE)
        {
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelBtnTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            }];
            
            UIAlertAction *comfirmAction = [UIAlertAction actionWithTitle:comfirmBtnTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                NSString *folderPath = [self getImageFolderPath:self.pathId];
                [[NSFileManager defaultManager]removeItemAtPath:folderPath error:nil];
                [self.navigationController popViewControllerAnimated:NO];
            }];
            
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:tipTitle
                                                                                     message:tipMsg
                                                                              preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:cancelAction];
            [alertController addAction:comfirmAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        else
        {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:tipTitle
                                                               message:tipMsg
                                                              delegate:self
                                                     cancelButtonTitle:cancelBtnTitle
                                                     otherButtonTitles:comfirmBtnTitle, nil];
            alertView.delegate = self;
            alertView.tag = 1001;
            [alertView show];
            [alertView release];
        }
    }
    else
    {
        [self.navigationController popViewControllerAnimated:NO];
    }
}

#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imageList.count;
}

//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"KAddItemCell";
    AddItemCell *cell = (AddItemCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    [cell sizeToFit];
    
    if (!cell)
    {
        NSLog(@"无法创建CollectionViewCell时打印，自定义的cell就不可能进来了。");
    }
    
    cell.pathId = [self.imageList objectAtIndex:indexPath.row];
    cell.delegate = self;
    
    if([cell.pathId isEqualToString:@"AddNewItemViewController_Add"])
    {
        cell.showImageView.image = [UIImage imageNamed:@"add_style"];
    }
    else
    {
        NSData *imageData = [[NSData alloc]initWithContentsOfFile:cell.pathId];
        if (imageData.length > 0)
        {
            UIImage *image = [[UIImage alloc]initWithData:imageData];
            cell.showImageView.image = image;
            [image release];
        }
        
        [imageData release];
    }
    
    return cell;
}

#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize cellSize = CGSizeMake(66, 66);
    if (isPhone())
    {
        cellSize = CGSizeMake(55, 55);
    }
    
    return cellSize;
}

//定义每个UICollectionView 的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    UIEdgeInsets cellEdgeInsets = UIEdgeInsetsMake(20, 30, 20, 30);
    if (isPhone())
    {
        cellEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 15);
    }
    
    return cellEdgeInsets;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section;
{
    if (isPhone())
    {
        return 10;
    }
    
    return 30;
}

#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"选择%ld",(long)indexPath.row);
    
    AddItemCell *cell = (AddItemCell *)[collectionView cellForItemAtIndexPath:indexPath];
    if([cell.pathId isEqualToString:@"AddNewItemViewController_Add"])
    {
        if (self.imageList.count > KMaxItemCount)
        {
            NSString *tipTitle = NSLocalizedString(@"add_style_max_title",nil);
            NSString *tipMsg = NSLocalizedString(@"add_style_max_msg",nil);
            NSString *cancelBtnTitle = NSLocalizedString(@"comfirm",nil);
            
            if (IOS_VERSION_8_OR_ABOVE)
            {
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelBtnTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                }];

                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:tipTitle
                                                                                         message:tipMsg
                                                                                  preferredStyle:UIAlertControllerStyleAlert];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
            else
            {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:tipTitle
                                                                   message:tipMsg
                                                                  delegate:self
                                                         cancelButtonTitle:cancelBtnTitle
                                                         otherButtonTitles:nil];
                alertView.delegate = self;
                alertView.tag = 1000;
                [alertView show];
                [alertView release];
            }
        }
        else
        {
            BOOL isAvailablForPhotoLibrary = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
            if (isAvailablForPhotoLibrary)
            {
                [self showAlbum];
            }
        }
    }
    else
    {
        
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1001)
    {
        if (buttonIndex == 1)
        {
            [self.navigationController popViewControllerAnimated:NO];
        }
    }
}

- (void)showAlbum
{
    UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.delegate = self;
    
    [self presentViewController:imagePickerController
                       animated:YES
                     completion:nil];
    
    [imagePickerController release];
}

//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#pragma mark -AddItemCellDelegate

- (void)goToDelete:(AddItemCell *)cell
{
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    [[NSFileManager defaultManager]removeItemAtPath:cell.pathId error:nil];
    NSArray *deleteArr = [NSArray arrayWithObject:indexPath];
    [self.imageList removeObjectAtIndex:indexPath.row];
    [self.collectionView deleteItemsAtIndexPaths:deleteArr];
}

#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingImage:(UIImage *)image
                  editingInfo:(NSDictionary *)editingInfo
{
    UIImage *editImage = image;
    CGSize editImageSize = image.size;
    CGSize drawSize = CGSizeMake(132, 132);
    
    if (!CGSizeEqualToSize(editImageSize, drawSize))
    {
        UIGraphicsBeginImageContextWithOptions(drawSize, 0, 1.0);
        [editImage drawInRect:CGRectMake(0,0,drawSize.width,drawSize.height)];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        if ([self isNewImage:newImage])
        {
            NSData *imageData = UIImagePNGRepresentation(newImage);
            NSString *folderPath = [self getImageFolderPath:self.pathId];
            double nowTime = [[NSDate date] timeIntervalSince1970];
            NSString *imagePath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%lld.png",(long long)nowTime]];
            [imageData writeToFile:imagePath atomically:YES];
            
            [self refreshTableUI];
        }
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)isNewImage:(UIImage *)image
{
    NSArray *paths = [self getImagePathListForFolderName:self.pathId];
    for (NSString *path in paths)
    {
        UIImage *image2 = [[UIImage alloc]initWithContentsOfFile:path];
        if ([self compareImage:image withImage:image2])
        {
            [image2 release];
            return NO;
        }
        [image2 release];
    }
    
    return YES;
}

-(BOOL)compareImage:(UIImage *)image1 withImage:(UIImage *)image2
{
    CGImageRef imageRef1 = image1.CGImage;
    CGImageRef imageRef2 = image2.CGImage;
    
    NSUInteger width1 = CGImageGetWidth(imageRef1);
    NSUInteger height1 = CGImageGetHeight(imageRef1);
    NSUInteger width2 = CGImageGetWidth(imageRef2);
    NSUInteger height2 = CGImageGetHeight(imageRef2);
    
    if ((width1 != width2) || (height1 != height2))
    {
        return NO;
    }
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    unsigned char *rawData1 = malloc(height1 * width1 * 4);
    unsigned char *rawData2 = malloc(height2 * width2 * 4);
    
    NSUInteger bytesPerPixel = 4;
    NSUInteger bitsPerComponent = 8;
    
    NSUInteger bytesPerRow1 = bytesPerPixel * width1;
    NSUInteger bytesPerRow2 = bytesPerPixel * width2;
    
    CGContextRef context1 = CGBitmapContextCreate(rawData1, width1, height1,
                                                 bitsPerComponent, bytesPerRow1, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGContextRef context2 = CGBitmapContextCreate(rawData2, width2, height2,
                                                  bitsPerComponent, bytesPerRow2, colorSpace,
                                                  kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    
    CGContextDrawImage(context1, CGRectMake(0, 0, width1, height1), imageRef1);
    CGContextRelease(context1);
    
    CGContextDrawImage(context2, CGRectMake(0, 0, width2, height2), imageRef2);
    CGContextRelease(context2);
    
    long allPoint = width1 * height1;
    long differencePoint = 0;
    
    for (int y = 0; y < height1; y++)
    {
        for (int x = 0; x < width1; x++)
        {
            long index = 4 * (y * width1 + x);
            
            BOOL red_dif = abs(rawData1[index] - rawData2[index]) > 1;
            BOOL green_dif = abs(rawData1[index + 1] - rawData2[index + 1]) > 1;
            BOOL blue_dif = abs(rawData1[index + 2] - rawData2[index + 2]) > 1;
            BOOL alpha_dif = abs(rawData1[index + 3] - rawData2[index + 3]) > 1;
            
            if (red_dif || green_dif || blue_dif || alpha_dif)
            {
                differencePoint++;
            }
            
            if (differencePoint >= 0.05 * allPoint)
            {
                if (rawData1 != NULL)
                {
                    free(rawData1);
                    rawData1 = NULL;
                }
                
                if (rawData2 != NULL)
                {
                    free(rawData2);
                    rawData2 = NULL;
                }
                
                return NO;
            }
        }
    }
    
    if (rawData1 != NULL)
    {
        free(rawData1);
        rawData1 = NULL;
    }
    
    if (rawData2 != NULL)
    {
        free(rawData2);
        rawData2 = NULL;
    }
    
    return YES;
}

@end
